from machine import Pin, SPI, I2C
from sdcard import *
import _thread
import time
import os

sd = SDCard(SPI(1, 20000000, sck=Pin(14), mosi=Pin(15), miso=Pin(2)), Pin(13))
os.mount(sd, '/sd')
os.chdir("/sd")

nextto = True
wifi = True

from lib.sh1106 import SH1106_I2C
from lib import *

i2c = I2C(scl=Pin(16), sda=Pin(17), freq=10000000)
display = SH1106_I2C(128, 64, i2c, None, 0x3c)
display.invert(False)
display.rotate(True)

def wifi():
    global nextto
    global wifi
    ssid_list = []
    ico(display, computer, 0, 108)
    fill(display, 0, 110, 10, 10, fill=0)
    ico(display, wifi_off, 0, 118)
    display.show()
    if not wlan.isconnected():
        while True:
            if wifi == False:break
            rs = wlan.scan()
            for w in rs:ssid_list.append(w[0])
            for si in sipd:
                if si.encode() in ssid_list:
                    nextto = False
                    start_time = time.time()
                    wlan.connect(si, sipd[si])
                    while not wlan.isconnected():
                        if time.time()-start_time > 15:break
                else:continue
            if wlan.isconnected():break
    try:
        ntptime.settime()
        fill(display, 0, 110, 10, 10, fill=0)
        ico(display, wifi_on, 0, 118)
        display.show()
    except:
        pass
    nextto = True
_thread.start_new_thread(wifi, ())

programs = {}
pro = os.listdir('/sd/system')

cho = 1
display.fill(0)
display.text(str(cho), 0, 54, 1)
display.show()

u = 10
a = 1
for i in pro:
    programs[str(a)] = i
    display.text(i, 0,u,1)
    u = u + 10
    a = a + 1
display.show()

k = Pin(5, Pin.IN)
while True:
    while True:
        if k.value() != 1:break

    last = time.ticks_ms()
    while True:
        if k.value() == 1:break
        if time.ticks_ms() - last >= 1200:break
    now = time.ticks_ms() - last
    time.sleep(0.1)
    print(now)
    if now <= 10:continue
    if now >=1200:
        break
    else:
        if cho == len(pro):
            display.text(str(cho), 0, 54, 0)
            cho = 1
        else:
            display.text(str(cho-1), 0, 54, 0)
            cho = cho+1
    display.text(str(cho), 0, 54, 1)
    display.show()
display.fill(0)
display.show()
while True:
    if nextto == True:break
wifi = False
execfile('/sd/system/{n}/main.py'.format(n=programs[str(cho)]))